#include <windows.h>
#include <iostream>
#include <stdio.h>
using namespace std;


static LPCTSTR g_szMutexName = L"w2kdg.ProcTerm.mutex.Suicide";

void StartClone() {
	TCHAR szFilename[MAX_PATH];
	GetModuleFileName(NULL, szFilename, MAX_PATH);
	TCHAR szCmdLine[MAX_PATH];
	wsprintf(szCmdLine, L"\"%s\" child", szFilename);

	STARTUPINFO si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	PROCESS_INFORMATION pi;

	BOOL bCreateOK = CreateProcess(szFilename, szCmdLine, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
	if (bCreateOK) {
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
	}
}

void Parent() {
	HANDLE hMutexSuicide = CreateMutex(NULL, TRUE, g_szMutexName);
	if (hMutexSuicide != NULL) {
		cout << "Creating the child process" << endl;
		StartClone();
		cout << "Telling the child process to quit." << endl;
		getchar();
		ReleaseMutex(hMutexSuicide);
		CloseHandle(hMutexSuicide);
	}

}

void Child() {
	HANDLE hMutexSuicide = OpenMutex(SYNCHRONIZE, FALSE, g_szMutexName);
	if (hMutexSuicide != NULL) {
		cout << "Child waiting for suicide instructions. " << endl;
		WaitForSingleObject(hMutexSuicide, INFINITE);
		cout << "Child quiting." << endl;
		CloseHandle(hMutexSuicide);
	}

}


int main(int argc, char *argv[]) {
	if (argc > 1 && strcmp(argv[1], "child") == 0) {
		Child();
	}
	else {
		Parent();
	}
	return 0;
}


